import numpy as np
import csv
import random
from datetime import datetime
from time import strftime

'''
Global and Local Empirical Bayes Smoothers with Gamma Model
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "begin at " + getCurTime()

    region1 = [9,23,25,33,34,36,42,44,50]
    region2 = [17,18,19,20,26,27,29,31,38,39,46,55]
    region3 = [1,5,10,11,12,13,21,22,24,28,37,40,45,47,48,51,54]
    region4 = [2,4,6,8,15,16,30,32,35,41,49,53,56]

    filepath = 'C:/_DATA/migration89_08/COUNTY Migration/clean/distinct_fips.csv'
    data = build_data_list(filepath)

    region = []
    for item in data[:,2]:
        if item in region1:
            region.append(1)
        elif item in region2:
            region.append(2)
        elif item in region3:
            region.append(3)
        elif item in region4:
            region.append(4)

    print region
    np.savetxt(filepath[:-4] + '_region.csv', region, delimiter=',', fmt = '%10.5f')
    